package com.gutai.admin.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Arrays;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.gutai.admin.common.entity.response.Response;
import com.gutai.admin.common.util.ResponseHelper;
import com.gutai.admin.service.IFileService;

@RestController
@RequestMapping(value = "/upload")
public class FileUploadController {

    private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class);

    public static final String ROOT = "upload-dir";

    private final ResourceLoader resourceLoader;
    @Autowired
    private IFileService fileService;
    /**支持图片的类型**/
    private String [] types={".jpg",".bmp",".jpeg",".png"};

    private final String PATH = "D:\\img";
    @Autowired
    public FileUploadController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @CrossOrigin
    @RequestMapping(value = "/image",method = RequestMethod.POST)
    public Response upload(HttpServletRequest request, HttpServletResponse response,
            @RequestParam(value = "file", required = true) MultipartFile file) throws Exception {
        String fileName = "";
        Map<String, String[]> parameterMap = request.getParameterMap();
        if (!file.isEmpty()) {
            fileName = file.getOriginalFilename();
            String type = fileName.substring(fileName.lastIndexOf("."));
            if (Arrays.asList(types).contains(type)) {
                // 保存 File位置 （全路径） /upload/fileName
                String url = request.getSession().getServletContext().getRealPath("/upload/");

                BufferedOutputStream out = null;
                File fileSourcePath = new File(url); // File fileSourcePath =
                                                     // new File(PATH);
                if (!fileSourcePath.exists()) {
                    fileSourcePath.mkdirs();
                }
                fileName = file.getOriginalFilename();
                logger.info("上传的文件名为：" + url + fileName);
                out = new BufferedOutputStream(new FileOutputStream(new File(fileSourcePath,
                        fileName)));
                out.write(file.getBytes());
                out.flush();
                out.close();
                System.out.println(fileName.toString());
                /**
                 * upload file
                 */
                String clazz[] = parameterMap.get("clazz");
                String columnName[] = parameterMap.get("columnName");
                System.out.println("clazz :" + clazz[0] + ",columnName:" + columnName[0]);
                if (clazz.length != 1 || columnName.length != 1) {
                    return ResponseHelper.buildFail("缺少类或列表参数。");
                }
                // File convFile = new File(file.getOriginalFilename());
                // file.transferTo(convFile);
                String OSSURI = fileService.putObject("gutai-zz", clazz[0], columnName[0],
                    new File(url + fileName));
                if (null != OSSURI) {
                    logger.info("ossuri is : {}", OSSURI);
                    return ResponseHelper.buildOk(OSSURI);
                }
                return ResponseHelper.buildFail("上传失败。");
            }
            return ResponseHelper.buildFail("不支持格式。");
        }
        return ResponseHelper.buildFail("图片为空");
    }

}
